﻿using IFRS.DataAccess.DAL;
using IFRS.Models;
using IFRS.Web;
using IFRS_Global;
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class IFRS_WIN12_2E : PageBase
{
    #region "---------- Events -----------"
    bool ValidIDCard = false;
    bool ValidEmptyLic = false;
    bool ValidEmptyIss = false;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!(Page.IsPostBack || Page.IsCallback))
        {
            this.AddClientScript();
            this.ViewMenu();
            this.SetErrorMessage();
            if (Request.QueryString["id"] != null)
            {
                this.BindData(Convert.ToInt32(Request.QueryString["id"].ToString()));
            }
            SetReadonly();
        }
        else
            ClientScript.RegisterHiddenField("isPostBack", "1");
    }

    protected void btnSAVE_Click(object sender, EventArgs e)
    {
        if (ValidIDCard && ValidEmptyLic && ValidEmptyIss) SaveData();
        ValidIDCard = false;
        ValidEmptyLic = false;
        ValidEmptyIss = false;
    }
    protected void btnCANCEL_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/IFRS/WIN12_1S.aspx");
    }   

    protected void CheckIDCard(object source, ServerValidateEventArgs args)
    {
        if (rbtCustpmerType_Firms.Checked)
        {
            args.IsValid = true;
            ValidIDCard = true;
            return;
        }
        int pin = 0;
        int j = 13;
        int pin_num = 0;
        string CardId = args.Value.Replace("-","");
        if (CardId == "")
        {
            args.IsValid = false;
            ValidIDCard = false;
            return;
        }
        if (CardId.Length == 13)
        {
            for (int i = 0; i < CardId.Length; i++)
            {
                if (i != 12)
                {
                    pin = Convert.ToInt16(CardId.Substring(i, 1)) * j + pin;
                }
                j--;
            }
            pin_num = (11 - (pin % 11)) % 10;
            if (Convert.ToInt16(CardId.Substring(12, 1)) != pin_num)
            {
                args.IsValid = false;
                ValidIDCard = false;
                return;
            }
        }
        else
        {
            args.IsValid = false;
            ValidIDCard = false;
            return;
        }
        args.IsValid = true;
        ValidIDCard = true;
        return;
    }
    protected void ValidateLicenseNoEmpty(object source, ServerValidateEventArgs args)
    {
        if (rbtCustpmerType_Firms.Checked)
        {
            if (string.IsNullOrEmpty(txtLicenseNo.Text))
            {
                args.IsValid = false;
                ValidEmptyLic = false;
            }
            else
            {
                args.IsValid = true;
                ValidEmptyLic = true;
            }
        }
        else
        {
            args.IsValid = true;
            ValidEmptyLic = true;
        }
        return;
    }
    protected void ValidateIssueAmountEmpty(object source, ServerValidateEventArgs args)
    {
        if (rbtCustpmerType_Firms.Checked)
        {
            if (txtIssueAmount.Text.AsDecimal() <= 0)
            {
                args.IsValid = false;
                ValidEmptyIss = false;
            }
            else
            {
                args.IsValid = true;
                ValidEmptyIss = true;
            }
        }
        else
        {
            args.IsValid = true;
            ValidEmptyIss = true;
        }
        return;
    }
    #endregion "---------- Events -----------"

    #region "----------  Methods -----------"

    private void AddClientScript()
    {
        btnCANCEL.Attributes["OnClick"] = "if(!confirm(\"" + Resources.ifrsResource.ConfirmCancel + "\")) return false;";
    }

    private void ViewMenu()
    {
        MenuTitleBar = Resources.ifrsMenu.WIN12_2E;
    }

    private void SetErrorMessage()
    {
        btnSAVE.ValidationGroup = "Master";
        reqCustomerCode.SetRequiredField(lblCustomerCode, txtCustomerCode, btnSAVE);
        reqIssueAmount.ErrorMessage = string.Format("{0}{1}{2}", "<BR>", lblIssueAmount.Text, " ต้องมากกว่า 0");
        reqLicenseNo.ErrorMessage = string.Format("{0}{1}{2}", "<BR>", Resources.ifrsField.PLEASE_IDENTIFIEND, lblLicenseNo.Text);
    }

    private void BindData(int ID)
    {
        List<Customer> customer = new List<Customer>();
        DataTable dt = new SPR_CUSTOMER().SEARCH_BYID(ID);
        if (dt.Rows.Count > 0)
        {
            ConvertHelper.ConvertDataTableToObject(dt, customer);
            txtCustomerCode.Text = customer[0].CustomerCode;
            rbtCustpmerType_Individuals.Checked = customer[0].CustomerType == 1 ? true : false;
            rbtCustpmerType_Firms.Checked = customer[0].CustomerType == 2 ? true : false;
            if(customer[0].CustomerType == 1)
                txtLicenseCardNo.Text = customer[0].LicenseNo;
            else
                txtLicenseNo.Text = customer[0].LicenseNo;

            txtPassportNo.Text = customer[0].PassportNo;
            txtIssueAmount.Text = customer[0].IssueAmount.DecimalToString();
            rbtStockExChangeRegister.SelectedValue = customer[0].StockExchangeRegister.IntToString();
            rbtOccupationType.SelectedValue = customer[0].OccupationType.IntToString();
            rbtResidentArea.SelectedValue = customer[0].ResidentArea.IntToString();
        }
    }

    private void SaveData()
    {
        try
        {
            Customer customer = new Customer();
            customer.CustomerID = Convert.ToInt32(Request.QueryString["id"].ToString());
            customer.SourceName = "";
            customer.CustomerCode = txtCustomerCode.Text;
            customer.CustomerType = rbtCustpmerType_Individuals.Checked ? 1 : 2;
            customer.LicenseNo = rbtCustpmerType_Individuals.Checked ? txtLicenseCardNo.Text : txtLicenseNo.Text;
            customer.PassportNo = txtPassportNo.Text;
            customer.IssueAmount = txtIssueAmount.Text.AsDecimal();
            if (rbtCustpmerType_Firms.Checked)
            {
                customer.StockExchangeRegister = rbtStockExChangeRegister.SelectedValue.AsIntIsnull();
            }
            else
            {
                customer.StockExchangeRegister = null;
            }
            customer.OccupationType = rbtOccupationType.SelectedValue.AsIntIsnull();
            customer.ResidentArea = rbtResidentArea.SelectedValue.AsInt32();
            customer.SetStandardField();

            int result = new SPR_CUSTOMER().UPDATE(customer);

            if (result > 0)
            {
                this.JS_Alert(Resources.ifrsResource.SaveData, ResolveUrl(string.Format("~/IFRS/WIN12_2E.aspx?&id={0}", customer.CustomerID)));

            }
            else
            {
                if (result == -1)
                {
                    Utility.AlertMessage(Page, Resources.ifrsResource.Duplicate);
                }
                else
                {
                    Utility.AlertMessage(Page, Resources.ifrsResource.CanNotSaveData);
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    private void SetReadonly()
    {
        if (rbtCustpmerType_Individuals.Checked)
        {
            txtLicenseNo.Attributes["readOnly"] = "true";
            txtLicenseNo.Style.Add("background-color", "#E0E0E0");

            txtIssueAmount.Attributes["readOnly"] = "true";
            txtIssueAmount.Style.Add("background-color", "#E0E0E0");
        }
        else
        {
            txtLicenseCardNo.Attributes["readOnly"] = "true";
            txtLicenseCardNo.Style.Add("background-color", "#E0E0E0");

            txtPassportNo.Attributes["readOnly"] = "true";
            txtPassportNo.Style.Add("background-color", "#E0E0E0");
        }
    }
    #endregion "----------  Methods -----------"
}